package com.niiwoo.civet.user.service.duboo.dataflow;

import com.alibaba.dubbo.config.annotation.Service;
import com.alibaba.fastjson.JSON;
import com.niiwoo.civet.user.dao.entity.DataBackflowRetryTask;
import com.niiwoo.civet.user.dto.request.DataBackFlowRetryTaskRequestDTO;
import com.niiwoo.civet.user.service.dataflow.DataBackFlowRetryDubboService;
import com.niiwoo.civet.user.service.local.dataflow.DataBackFlowRetryService;
import com.niiwoo.tripod.tiancheng.enums.FunctionCodeEnum;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;

import java.util.concurrent.TimeUnit;

/**
 * @Author: wuke
 * @Description: 数据回流重试服务
 * @Date: Created in 18:00 2018/1/10
 */
@Slf4j
@Service(version = "1.0.0")
public class DataBackFlowRetryDubboServiceImpl implements DataBackFlowRetryDubboService {
    @Autowired
    private DataBackFlowRetryService dataBackFlowRetryService;
    @Autowired
    private RedisTemplate<String, String> redisTemplate;
    private final String DATA_BACK_FLOW_RETRY_TASK_LOCK = "dataBackFlowRetryTaskLock";

    /**
     * 保存数据回流重试任务数据
     * @param dataBackFlowRetryTaskRequestDTO
     */
    public void saveDataFlowRetryTask(DataBackFlowRetryTaskRequestDTO dataBackFlowRetryTaskRequestDTO){
        String functionCode = dataBackFlowRetryTaskRequestDTO.getFunctionCode();
        FunctionCodeEnum functionCodeEnum = FunctionCodeEnum.getByBodyFunctionCode(functionCode);
        log.info("saveDataFlowRetryTask.functionCodeEnum={}",JSON.toJSONString(functionCodeEnum));
        if(functionCodeEnum==null){
            log.info("saveDataFlowRetryTask.functionCodeEnum为空");
            return;
        }
        DataBackflowRetryTask dataBackflowRetryTask = new DataBackflowRetryTask();
        dataBackflowRetryTask.setUserId(dataBackFlowRetryTaskRequestDTO.getUserId());
        dataBackflowRetryTask.setFunctionCode(functionCode);
        dataBackflowRetryTask.setFunctionName(functionCodeEnum.getDesc());
        dataBackflowRetryTask.setBackflowData(dataBackFlowRetryTaskRequestDTO.getBackflowData());
        dataBackFlowRetryService.saveDataFlowRetryTask(dataBackflowRetryTask);
    }

    public void dataBackFlowRetry(){
        Boolean notExists = redisTemplate.opsForValue().setIfAbsent(DATA_BACK_FLOW_RETRY_TASK_LOCK, "");
        if (!notExists) {
            log.info("已有dataBackFlowRetry任务在执行");
            return;
        }
        redisTemplate.expire(DATA_BACK_FLOW_RETRY_TASK_LOCK, 1, TimeUnit.HOURS);
        try {
            log.info("dataBackFlowRetry开始执行");
            dataBackFlowRetryService.sendDataBackFlowRetry();
        } catch (Exception e) {
            log.error("dataBackFlowRetry异常",e);
        }finally {
            //删除锁定表示
            redisTemplate.delete(DATA_BACK_FLOW_RETRY_TASK_LOCK);
        }
        log.info("dataBackFlowRetry结束执行");
    }
}
